<template>
  <div class="block" style="line-height: 100px;text-align: center;" v-if="isLogin">
    <el-dropdown>
          <span class="el-dropdown-link">
            {{ userdata.username }}
            <el-icon class="el-icon--right">
              <el-avatar :size="20" :src="userdata.usericon"></el-avatar>
            </el-icon>
          </span>
      <template #dropdown>
        <el-dropdown-menu>
          <el-dropdown-item @click="centerDialogVisible=true">修改个人信息</el-dropdown-item>
          <el-dropdown-item divided @click="signOut">退出</el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>
  </div>
  <div v-else>
    <el-button type="primary" round @click="doLogin">去登录</el-button>
  </div>


  <el-dialog
      v-model="centerDialogVisible"
      title="修改个人信息"
      width="30%"
      destroy-on-close
      center
  >
    <span>在此处修改个人信息</span>
    <div>
      <strong>可以添加友链</strong>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-form ref="upUserInfoForm" :model="userdata" :rules="userRules">
        <el-form-item prop="username">
          <el-input type="text" v-model="userdata.username" placeholder="请输入用户名" :prefix-icon="Avatar"></el-input>
        </el-form-item>
        <el-form-item prop="email">
          <el-input type="text" v-model="userdata.email" placeholder="请输入邮箱" :prefix-icon="ChatDotSquare"></el-input>
        </el-form-item>
        <el-form-item prop="friend_chain">
          <el-input type="text" v-model="userdata.friend_chain" placeholder="请输入友链"
                    :prefix-icon="ChatDotSquare"></el-input>
        </el-form-item>
        <el-form-item>
          <el-upload
              class="avatar-uploader"
              action="api/blog/v1/uploadRes"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
          >
            <img v-if="userdata.usericon" :src="userdata.usericon" class="avatar"/>
            <el-icon v-else class="avatar-uploader-icon">
              <plus/>
            </el-icon>
          </el-upload>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="upUserInfo">
            确认
          </el-button>
          <el-button type="info" @click="centerDialogVisible = false">
            取消
          </el-button>
        </el-form-item>

      </el-form>
      </span>
    </template>
  </el-dialog>

</template>

<script lang="ts">
import {defineComponent, reactive, ref} from "vue";
import LoginRequest from "@/utils/login";
import request from "@/utils/request";
import route from "@/router";
import {ElMessage} from "element-plus";
import {ChatDotSquare, Avatar, Plus} from "@element-plus/icons";

export default defineComponent({
  name: 'UserInfo',
  components: {
    Plus

  },
  setup() {
    const isLogin = ref(LoginRequest.isLogin())
    const userdata = reactive({
      username: LoginRequest.getUserName(),
      usericon: LoginRequest.getUserIcon(),
      email: LoginRequest.getEmail(),
      friend_chain: LoginRequest.getFriendChain(),
    })
    const upUserInfoForm = ref(null)
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback()
      } else {
        if (upUserInfoForm.value.password !== '') {
          upUserInfoForm.value.validateField('password')
        }
        callback()
      }
    }
    const validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('确认密码不能为空'))
      } else if (value !== upUserInfoForm.value.password) {
        callback(new Error("确认密码与密码不一致"))
      } else {
        callback()
      }
    }

    // 邮箱
    const email = (rule, value, callback) => {
      const mal = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/
      if (rule.required && value === "") {
        return callback(new Error('邮箱不能为空'))
      }
      if (value !== "") {
        if (!(mal.test(value))) {
          callback(new Error('邮箱地址不正确'))
        } else {
          callback()
        }
      }
    }

    // 设置手机号的验证规则
    const phone = (rule, value, callback) => {
      if (rule.required && value === "") {
        callback(new Error('手机号不能为空'))
      } else {
        const reg = /^1[3|4|5|6|7|8|9]\d{9}$/
        if (reg.test(value)) {
          callback()
        } else {
          return callback(new Error('请输入正确的电话'))
        }
      }
    }

    const userRules = {
      username: [
        {
          required: true,
          message: '请输入用户名',
          trigger: 'blur',
        },
        {
          min: 3,
          max: 10,
          message: '用户名长度在3-10个字符之间',
          trigger: 'blur',
        },
      ],
      phone: [
        {
          validator: phone,
          trigger: 'blur',
        }
      ],
      email: [
        {
          validator: email,
          trigger: 'blur',
        }
      ],
    }
    const centerDialogVisible = ref(false)

    const upUserInfo = async () => {

      await request.post("upInfo", userdata).then((res: any) => {
        if (res.code == 200) {
          LoginRequest.setFriendChain(userdata.friend_chain)
          ElMessage.success("更新成功")
        }
      })
      centerDialogVisible.value = false
      return false
    }
    const doLogin = () => {
      route.push({path: '/Login',})
    }

    const handleAvatarSuccess = (res: any) => {
      if (res.code == 200) {
        userdata.usericon = res.data.resources_url
      }
    }

    const beforeAvatarUpload = (file) => {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        ElMessage.error('头像图片必须为JPG格式!')
      }
      if (!isLt2M) {
        ElMessage.error('头像图片大小不能超过2MB!')
      }
      return isJPG && isLt2M
    }

    const signOut = () => {
      LoginRequest.signOut()
      userdata.username = LoginRequest.getUserName()
      userdata.usericon = LoginRequest.getUserIcon()
      userdata.email = LoginRequest.getEmail()
      userdata.friend_chain = LoginRequest.getFriendChain()
      isLogin.value = false
    }

    return {
      isLogin,
      userdata,
      centerDialogVisible,
      userRules,
      upUserInfoForm,
      ChatDotSquare,
      Avatar,
      upUserInfo,
      doLogin,
      handleAvatarSuccess,
      beforeAvatarUpload,
      signOut
    }
  }
})
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.avatar-uploader-icon svg {
  margin-top: 74px; /* (178px - 28px) / 2 - 1px */
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>